import {
  cleanString,
  normalizeWeight,
  normalizeWeightInSize,
  normalizeDimensions,
} from "./utils";

// #region [美国]
// 尝试解析美国站点常见的尺寸格式，如：`10 x 20 x 30 inches` 或 `10 x 20 x 30 in`
function parseUsaDimensions(value: string) {
  type DimensionKey = "depth" | "width" | "height" | "length";
  type DimensionLetter = "D" | "W" | "H" | "L";
  // 定义关键词映射
  const keywordMap: Record<DimensionLetter, DimensionKey> = {
    D: "depth",
    W: "width",
    H: "height",
    L: "length",
  };
  const isDimensionLetter = (v: string): v is DimensionLetter =>
    v === "D" || v === "W" || v === "H" || v === "L";

  // 检查是否为 "154D x 76W x 113H Centimetres" 格式
  if (/Centimetres/i.test(value)) {
    // 匹配数字和维度标识符
    const parts = value.match(/(\d+\.?\d*)([DWH]|L)/gi);
    if (parts && parts.length >= 2) {
      const dimensions: Record<DimensionKey, number> = {
        depth: 0,
        width: 0,
        height: 0,
        length: 0,
      };

      parts.forEach((part) => {
        // 提取数字和单位
        const numMatch = part.match(/(\d+\.?\d*)/);
        const unitMatch = part.match(/([DWH]|L)/i);

        if (numMatch && unitMatch) {
          const number = parseFloat(numMatch[0]);
          const unit = unitMatch[0].toUpperCase();

          if (unit && isDimensionLetter(unit)) {
            const dimensionKey: DimensionKey = keywordMap[unit];
            dimensions[dimensionKey] = number;
          }
        }
      });

      // 构造输出字符串，忽略值为 0 的维度
      const formattedDimensions: string[] = [];
      const order: DimensionKey[] = ["length", "depth", "width", "height"];
      order.forEach((key: DimensionKey) => {
        if (dimensions[key] > 0) {
          formattedDimensions.push(`${dimensions[key].toFixed(2)}cm`);
        }
      });

      return formattedDimensions.join(" x ");
    }
  }

  // 兼容原有格式（如 "46.6\"D x 19.7\"W x 29.5\"H"）
  else if (/"|'([DWH]|L)/i.test(value)) {
    // 提取数字和单位
    const parts = value.match(/(\d+\.?\d*)["']([DWH]|L)/gi);
    if (parts && parts.length >= 2) {
      const dimensions: Record<DimensionKey, number> = {
        depth: 0,
        width: 0,
        height: 0,
        length: 0,
      };

      parts.forEach((part) => {
        const numMatch = part.match(/(\d+\.?\d*)/);
        const unitMatch = part.match(/["']([DWH]|L)/i);

        if (numMatch && unitMatch) {
          const number = parseFloat(numMatch[0]);
          const unit = unitMatch[1].toUpperCase();

          if (isDimensionLetter(unit)) {
            const dimensionKey: DimensionKey = keywordMap[unit];
            dimensions[dimensionKey] = number * 2.54; // 英寸转厘米
          }
        }
      });

      // 构造输出字符串
      const formattedDimensions: string[] = [];
      const order: DimensionKey[] = ["length", "depth", "width", "height"];
      order.forEach((key: DimensionKey) => {
        if (dimensions[key] > 0) {
          formattedDimensions.push(`${dimensions[key].toFixed(2)}cm`);
        }
      });

      return formattedDimensions.join(" x ");
    }
  }

  // 处理 "9.65 x 6.42 x 0.67 inches" 格式
  else {
    if (/inches/i.test(value)) {
      // 匹配所有数字
      const parts = value.match(/(\d+\.?\d*)/g);
      if (parts && parts.length >= 2) {
        const dimensions: Record<DimensionKey, number> = {
          depth: 0,
          width: 0,
          height: 0,
          length: 0,
        };
        const dimensionKeys: DimensionKey[] = ["length", "width", "height"]; // 假设顺序

        parts.slice(0, 3).forEach((number, i) => {
          dimensions[dimensionKeys[i]] = parseFloat(number) * 2.54; // 英寸转厘米
        });

        // 构造输出字符串
        const formattedDimensions: string[] = [];
        const order: DimensionKey[] = ["length", "depth", "width", "height"];
        order.forEach((key: DimensionKey) => {
          if (dimensions[key] > 0) {
            formattedDimensions.push(`${dimensions[key].toFixed(2)}cm`);
          }
        });

        return formattedDimensions.join(" x ");
      }
    }
  }

  return "";
}

function parseUsaWeightFromDimension(
  dimStr: string,
  marketplace: string
): number {
  if (!dimStr) return 0;

  const weightValue = normalizeWeightInSize(dimStr, marketplace);
  if (weightValue) {
    return weightValue;
  }

  // // 匹配重量信息（支持阿拉伯语和英语单位，对应Python的re.search）
  // const kgWeightRegex = /(\d+[.,]?\d*)\s*(كيلو غرام|kg|كيلو|كغم|kilogram)/gi;
  // const kgWeightMatch = kgWeightRegex.exec(dimStr);

  // if (kgWeightMatch) {
  //   // 替换逗号为点号，转换为克并取整
  //   const kgWeightValue = kgWeightMatch[1].replace(",", ".");
  //   try {
  //     const gramValue = Math.round(parseFloat(kgWeightValue) * 1000);
  //     return gramValue;
  //   } catch (error) {
  //     console.warn(`无法转换重量值: ${kgWeightValue}`);
  //     return 0;
  //   }
  // }

  // console.warn(`未能从尺寸字段中提取重量: ${dimStr}`);
  return 0;
}
function parseUsaDimensionsAndWeight(value: string, marketplace: string) {
  const dimensionsData = parseUsaDimensions(value);
  const weightData = parseUsaWeightFromDimension(value, marketplace);
  return {
    dimensionsData,
    weightData,
  };
}
// 关键词可按需扩展
const DIMENSION_KEYWORDS = [
  "product dimensions",
  "item dimensions",
  "package dimensions",
  "dimensions",
  "item dimensions l x w x h",
  "item dimensions lxwxh",
];
const WEIGHT_KEYWORDS = [
  "item weight",
  "shipping weight",
  "package weight",
  "weight",
];
function extractUsaSpecs(doc: Document): {
  dimensions: string;
  weight: any;
  brand: string;
} {
  let dimensions = "";
  let weight: number | string = "";
  let brand = "";
  const marketplace = "USA";

  // 新样式：a-section a-spacing-small a-spacing-top-small → table.a-normal.a-spacing-micro
  const productDataTable = doc.querySelector(
    "div.a-section.a-spacing-small.a-spacing-top-small"
  );
  if (productDataTable) {
    const table = productDataTable.querySelector(
      "table.a-normal.a-spacing-micro"
    );
    if (table) {
      const rows = table.querySelectorAll('tr[role="listitem"]');
      rows.forEach((row: Element) => {
        const labelElem = row.querySelector("span.a-text-bold");
        const valueElem = row.querySelector("span.po-break-word");
        if (!labelElem || !valueElem) return;

        const label = cleanString(labelElem.textContent).toLowerCase();
        const value = cleanString(valueElem.textContent);

        if (
          !dimensions &&
          DIMENSION_KEYWORDS.some((kw) => label.includes(kw.toLowerCase()))
        ) {
          const { dimensionsData, weightData } = parseUsaDimensionsAndWeight(
            value,
            marketplace
          );
          dimensions = dimensionsData || value;

          if (!weight && weightData) {
            weight = weightData;
          }
        } else if (
          !weight &&
          WEIGHT_KEYWORDS.some((kw) => label.includes(kw.toLowerCase()))
        ) {
          weight = normalizeWeight(value, "USA");
        } else if (
          !brand &&
          ["brand", "manufacturer", "brand:"].includes(label)
        ) {
          brand = value;
        }
      });
    }
  }

  // 旧样式一：id=productDetails_detailBullets_sections1
  if (!dimensions || !weight || !brand) {
    const techSpecTable = doc.querySelector(
      "table#productDetails_detailBullets_sections1"
    );
    if (techSpecTable) {
      techSpecTable.querySelectorAll("tr").forEach((row: Element) => {
        const th = row.querySelector("th");
        const td = row.querySelector("td");
        if (!th || !td) return;

        const label = cleanString(th.textContent).toLowerCase();
        const value = cleanString(td.textContent);

        if (
          !dimensions &&
          DIMENSION_KEYWORDS.some((kw) => label.includes(kw.toLowerCase()))
        ) {
          const { dimensionsData, weightData } = parseUsaDimensionsAndWeight(
            value,
            marketplace
          );
          dimensions = dimensionsData || value;
          if (!weight && weightData) {
            weight = weightData;
          }
        } else if (
          !weight &&
          WEIGHT_KEYWORDS.some((kw) => label.includes(kw.toLowerCase()))
        ) {
          weight = normalizeWeight(value, "USA");
        } else if (
          !brand &&
          ["brand", "manufacturer", "brand:"].includes(label)
        ) {
          brand = value;
        }
      });
    }
  }

  // 旧样式二：id=productDetails_techSpec_section_1
  if (!dimensions || !weight || !brand) {
    const techSpecTable1 = doc.querySelector(
      "table#productDetails_techSpec_section_1"
    );
    if (techSpecTable1) {
      techSpecTable1.querySelectorAll("tr").forEach((row: Element) => {
        const th = row.querySelector("th");
        const td = row.querySelector("td");
        if (!th || !td) return;

        const label = cleanString(th.textContent).toLowerCase();
        const value = cleanString(td.textContent);

        if (
          !dimensions &&
          DIMENSION_KEYWORDS.some((kw) => label.includes(kw.toLowerCase()))
        ) {
          const { dimensionsData, weightData } = parseUsaDimensionsAndWeight(
            value,
            marketplace
          );
          dimensions = dimensionsData || value;
          if (!weight && weightData) {
            weight = weightData;
          }
        } else if (
          !weight &&
          WEIGHT_KEYWORDS.some((kw) => label.includes(kw.toLowerCase()))
        ) {
          weight = normalizeWeight(value, "USA");
        } else if (
          !brand &&
          ["brand", "manufacturer", "brand:"].includes(label)
        ) {
          brand = value;
        }
      });
    }
  }

  // poExpander 结构：div#poExpander → table[role="list"] → tr[role="listitem"]
  if (!dimensions || !weight || !brand) {
    const poExpander = doc.querySelector("div#poExpander");
    if (poExpander) {
      const table = poExpander.querySelector('table[role="list"]');
      if (table) {
        table
          .querySelectorAll('tr[role="listitem"]')
          .forEach((row: Element) => {
            const labelElem = row.querySelector("span.a-text-bold");
            const valueElem = row.querySelector("span.po-break-word");
            if (!labelElem || !valueElem) return;

            const label = cleanString(labelElem.textContent).toLowerCase();
            const value = cleanString(valueElem.textContent);

            if (
              !dimensions &&
              DIMENSION_KEYWORDS.some((kw) => label.includes(kw.toLowerCase()))
            ) {
              const { dimensionsData, weightData } =
                parseUsaDimensionsAndWeight(value, marketplace);
              dimensions = dimensionsData || value;
              if (!weight && weightData) {
                weight = weightData;
              }
            } else if (
              !weight &&
              WEIGHT_KEYWORDS.some((kw) => label.includes(kw.toLowerCase()))
            ) {
              weight = normalizeWeight(value, "USA");
            } else if (
              !brand &&
              ["brand", "manufacturer", "brand:"].includes(label)
            ) {
              brand = value;
            }
          });
      }
    }
  }

  // 回退：ul.detail-bullet-list
  if (!dimensions || !weight || !brand) {
    const specList = doc.querySelector('ul[class*="detail-bullet-list"]');
    if (specList) {
      specList.querySelectorAll("li").forEach((li: Element) => {
        const labelSpan = li.querySelector("span.a-text-bold");
        // 取无 class 的 span 作为值
        const valueSpan = Array.from(li.querySelectorAll("span")).find(
          (s) => !s.className || s.className === ""
        );
        if (!labelSpan || !valueSpan) return;

        const label = cleanString(labelSpan.textContent).toLowerCase();
        const value = cleanString(valueSpan.textContent);

        if (
          !dimensions &&
          DIMENSION_KEYWORDS.some((kw) => label.includes(kw.toLowerCase()))
        ) {
          const { dimensionsData, weightData } = parseUsaDimensionsAndWeight(
            value,
            marketplace
          );
          dimensions = dimensionsData || value;
          if (!weight && weightData) {
            weight = weightData;
          }
        } else if (
          !weight &&
          WEIGHT_KEYWORDS.some((kw) => label.includes(kw.toLowerCase()))
        ) {
          weight = normalizeWeight(value, "USA");
        } else if (
          !brand &&
          ["brand", "manufacturer", "brand:"].includes(label)
        ) {
          brand = value;
        }
      });
    }
  }

  return { dimensions, weight, brand };
}
// #endregion
// #region [日本]
/**
 * 解析尺寸和重量的混合字符串，支持多种格式
 * @param value 包含尺寸和重量的字符串
 * @returns [dimensions, weight] 提取到的尺寸和重量字符串（未匹配则为空字符串）
 */
function parseJpnDimensionsAndWeight(value: string): [string, string] {
  // 尺寸正则表达式：匹配 数字x数字x数字+单位（cm/mm/m）格式
  const dimensionPattern =
    /(\d+(\.\d+)?\s*[xX]\s*\d+(\.\d+)?\s*[xX]\s*\d+(\.\d+)?)\s*(cm|mm|m)/;
  // 重量正则表达式：匹配 数字+单位（g/kg）格式
  const weightPattern = /(\d+(\.\d+)?)\s*(g|kg)/;

  // 提取尺寸
  const dimensionMatch = value.match(dimensionPattern);
  const dimensions = dimensionMatch ? dimensionMatch[0] : "";

  // 提取重量
  const weightMatch = value.match(weightPattern);
  const weight = weightMatch ? weightMatch[0] : "";

  return [dimensions, weight];
}

/**
 * 将日本重量字符串转换为克（g）
 * @param weightStr 原始重量字符串
 * @returns 标准化后的重量（单位：g，未识别则返回0）
 */
function normalizeJpnWeight(weightStr: string): any {
  weightStr = weightStr.toLowerCase().replace(",", "");
  // 匹配 数字+单位（g/kg/グラム/キログラム）格式
  const match = weightStr.match(/(\d+\.?\d*)\s*(g|kg|グラム|キログラム)/);

  if (match) {
    const [, valueStr, unit] = match;
    const value = parseFloat(valueStr);

    // 千克（含日文）转克
    if (unit === "kg" || unit === "キログラム") {
      return Math.floor(value * 1000); // 转整数克（同Python int()效果）
    }
    // 克（含日文）直接返回
    else if (unit === "g" || unit === "グラム") {
      return Math.floor(value); // 转整数克
    }
  }

  return 0; // 未识别到有效重量返回0
}

const JPN_DIMENSION_KEYWORDS = [
  "製品サイズ",
  "寸法",
  "サイズ",
  "商品寸法",
  "梱包サイズ",
  "外装寸法",
];

const JPN_WEIGHT_KEYWORDS = ["重さ", "質量", "重量"];
function extractJpnSpecs(doc: Document): {
  dimensions: string;
  weight: any;
  brand: string;
} {
  let dimensions = "";
  let weight = "";
  let brand = "";

  // 从<table>结构提取
  const specTables = doc.querySelectorAll("table.prodDetTable");
  specTables.forEach((table) => {
    const rows = table.querySelectorAll("tr");
    rows.forEach((row) => {
      const header = row.querySelector("th");
      const value = row.querySelector("td");

      if (header && value) {
        const headerText = cleanString(header.textContent || "").toLowerCase();
        const valueText = cleanString(value.textContent || "");

        // 提取尺寸
        if (
          !dimensions &&
          JPN_DIMENSION_KEYWORDS.some((kw) => headerText.includes(kw))
        ) {
          const [extractedDimensions, extractedWeight] =
            parseJpnDimensionsAndWeight(valueText);
          dimensions = extractedDimensions;
          if (!weight && extractedWeight) {
            weight = normalizeJpnWeight(extractedWeight);
          }
        }

        // 提取重量
        else if (
          !weight &&
          JPN_WEIGHT_KEYWORDS.some((kw) => headerText.includes(kw))
        ) {
          weight = normalizeJpnWeight(valueText);
        }

        // 提取品牌
        else if (
          !brand &&
          ["ブランド", "製造元", "ブランド名"].some((kw) =>
            headerText.includes(kw)
          )
        ) {
          brand = valueText;
        }
      }
    });
  });

  // 从<ul>列表提取（如果表格中未获取完全）
  if (!dimensions || !weight || !brand) {
    const specList = Array.from(doc.querySelectorAll("ul")).find((ul) =>
      ul.classList.contains("detail-bullet-list")
    );

    if (specList) {
      const listItems = specList.querySelectorAll("li");
      listItems.forEach((li) => {
        const labelSpan = li.querySelector("span.a-text-bold");
        const valueSpan = li.querySelector("span:not([class])");

        if (labelSpan && valueSpan) {
          const header = cleanString(labelSpan.textContent || "").toLowerCase();
          const value = cleanString(valueSpan.textContent || "");

          // 提取尺寸
          if (
            !dimensions &&
            JPN_DIMENSION_KEYWORDS.some((kw) => header.includes(kw))
          ) {
            const [extractedDimensions, extractedWeight] =
              parseJpnDimensionsAndWeight(value);
            dimensions = extractedDimensions;
            if (!weight && extractedWeight) {
              weight = normalizeWeight(extractedWeight, "JPN");
            }
          }

          // 提取重量
          else if (
            !weight &&
            JPN_WEIGHT_KEYWORDS.some((kw) => header.includes(kw))
          ) {
            weight = normalizeWeight(value, "JPN");
          }

          // 提取品牌
          else if (
            !brand &&
            ["ブランド", "製造元", "ブランド名"].some((kw) =>
              header.includes(kw)
            )
          ) {
            brand = value;
          }
        }
      });
    }
  }

  return { dimensions, weight, brand };
}
// #endregion

// #region [德国]
const DEU_EXACT_DIMENSION_KEYWORDS = [
  "produktabmessungen",
  "abmessungen",
  "größe",
  "verpackungsabmessungen"
];
const DEU_WEIGHT_KEYWORDS = ["produktgewicht", "gewicht"];
const DEU_EXACT_WEIGHT_KEYWORDS = ["artikelgewicht"];
const DEU_BRAND_KEYWORDS = ["marke", "hersteller"];
function normalizeDeuDimensions(dimensionsStr: string) {
  return normalizeDimensions(dimensionsStr, "DEU");
}
function normalizeDeuWeight(weightStr: string) {
  return normalizeWeight(weightStr, "DEU");
}
function parseDeuDimensionsAndWeight(dimensionsStr: string) {
  const [dimensionsPart, weightPart] = dimensionsStr.split(";");
  const dimensionsData = normalizeDeuDimensions(dimensionsPart);
  const weightData = normalizeDeuWeight(weightPart);
  return {
    dimensionsData,
    weightData,
  };
}
function extractDeuSpecs(doc: Document): {
  dimensions: string;
  weight: any;
  brand: string;
} {
  let dimensions = "";
  let weight: number | string = "";
  let brand = "";
  const marketplace = "DEU";

  // 1. 优先处理通用表格结构（匹配class包含'detail-bullet-list'的ul）
  const specList = doc.querySelector('ul[class*="detail-bullet-list"]');
  if (specList) {
    // 遍历所有li元素（对应Python的spec_list.find_all('li')）
    const liElements = specList.querySelectorAll("li");
    liElements.forEach((li) => {
      // 查找带a-text-bold类的标签（对应Python的label_span）
      const labelSpan = li.querySelector("span.a-text-bold");
      // 查找无class的span标签（对应Python的value_span，class为None）
      const valueSpan = li.querySelector("span:not([class])");

      if (labelSpan && valueSpan) {
        const label = cleanString(labelSpan.textContent || "")
          .toLowerCase()
          .replace(/[ :]/g, "");
        const value = cleanString(valueSpan.textContent || "");

        // 匹配尺寸关键词（未找到时才赋值）
        if (
          !dimensions &&
          DEU_EXACT_DIMENSION_KEYWORDS.some((kw) => label === kw.toLowerCase())
        ) {
          // console.log("value", value);
          const { dimensionsData, weightData } =
            parseDeuDimensionsAndWeight(value);
          dimensions = dimensionsData || value;
          if (!weight && weightData) {
            weight = weightData;
          }
        }
        // 匹配重量关键词（未找到时才赋值）
        else if (
          !weight &&
          DEU_WEIGHT_KEYWORDS.some((kw) => label === kw.toLowerCase())
        ) {
          weight = normalizeWeight(value, marketplace);
        } else if (
          DEU_EXACT_WEIGHT_KEYWORDS.some((kw) =>
            label.includes(kw.toLowerCase())
          )
        ) {
          weight = normalizeWeight(value, marketplace);
        }
        // 匹配品牌/制造商关键词（未找到时才赋值）
        else if (
          !brand &&
          DEU_BRAND_KEYWORDS.some((kw) => label.includes(kw.toLowerCase()))
        ) {
          brand = value;
        }
      }
    });
  }

  // 2. 处理 productDetails_techSpec_section_1 表格
  const techSpecTable = doc.querySelector(
    "table#productDetails_techSpec_section_1"
  );
  if (techSpecTable) {
    techSpecTable.querySelectorAll("tr").forEach((row) => {
      const th = row.querySelector("th.a-color-secondary");
      const td = row.querySelector("td.a-size-base");

      if (th && td) {
        const label = cleanString(th.textContent || "").toLowerCase().replace(/[ :]/g, "");
        const value = cleanString(td.textContent || "");

        // 提取尺寸（取分号前部分）
        if (
          !dimensions &&
          DEU_EXACT_DIMENSION_KEYWORDS.some((kw) => label === kw.toLowerCase())
        ) {
          const { dimensionsData, weightData } =
            parseDeuDimensionsAndWeight(value);
          dimensions = dimensionsData || value;
          if (!weight && weightData) {
            weight = weightData;
          }
        }
        // 提取重量
        else if (
          !weight &&
          DEU_WEIGHT_KEYWORDS.some((kw) => label.includes(kw))
        ) {
          weight = normalizeDeuWeight(value);
        } else if (
          DEU_EXACT_WEIGHT_KEYWORDS.some((kw) => label === kw.toLowerCase())
        ) {
          weight = normalizeDeuWeight(value);
        }
        // 提取品牌
        else if (
          !brand &&
          DEU_BRAND_KEYWORDS.some((kw) => label.includes(kw))
        ) {
          brand = value;
        }
      }
    });
  }

  // 3. 兜底：从 productOverview_feature_div 提取（未获取完全时）
  if (!dimensions || !weight || !brand) {
    const overviewDiv = doc.querySelector("div#productOverview_feature_div");
    if (overviewDiv) {
      overviewDiv.querySelectorAll("tr").forEach((row) => {
        const tds = row.querySelectorAll("td");
        if (tds.length < 2) return;

        const label = cleanString(tds[0].textContent || "").toLowerCase().replace(/[ :]/g, "");
        const value = cleanString(tds[1].textContent || "");

        // 提取尺寸
        if (
          !dimensions &&
          DEU_EXACT_DIMENSION_KEYWORDS.some((kw) => label === kw.toLowerCase())
        ) {
          const { dimensionsData, weightData } =
            parseDeuDimensionsAndWeight(value);
          dimensions = dimensionsData || value;
          if (!weight && weightData) {
            weight = weightData;
          }
        }
        // 提取重量
        else if (
          !weight &&
          DEU_WEIGHT_KEYWORDS.some((kw) => label.includes(kw.toLowerCase()))
        ) {
          weight = normalizeDeuWeight(value);
        } else if (
          DEU_EXACT_WEIGHT_KEYWORDS.some((kw) => label === kw.toLowerCase())
        ) {
          weight = normalizeDeuWeight(value);
        }
        // 提取品牌
        else if (
          !brand &&
          DEU_BRAND_KEYWORDS.some((kw) => label.includes(kw.toLowerCase()))
        ) {
          brand = value;
        }
      });
    }
  }

  return { dimensions, weight, brand };
}

// #endregion

// #region [墨西哥]
// 墨西哥站点规格提取专用关键词
const MEX_DIMENSION_KEYWORDS = [
  "dimensiones del artículo",
  "dimensiones",
  "dimensiones del producto",
  "dimensiones del paquete",
];
const MEX_WEIGHT_KEYWORDS = [
  "peso del artículo",
  "peso",
  "peso del producto",
  "peso del paquete",
];
const MEX_BRAND_KEYWORDS = ["marca", "fabricante"];

/**
 * 分离尺寸和重量信息（处理 "尺寸; 重量" 格式）
 * @param value 原始混合字符串
 * @returns [dimensions, weight] 分离后的尺寸和重量
 */
function splitDimensionWeight(value: string): [string, string] {
  let dimensions = "";
  let weight = "";
  const parts = value.split(";").map((part) => part.trim());

  // 尺寸正则：匹配 数字x数字(x数字) + 单位（cm/m/in）
  const dimensionRegex =
    /\d+[\.,]?\d*\s*x\s*\d+[\.,]?\d*(\s*x\s*\d+[\.,]?\d*)?\s*(cm|m|in)/i;
  // 重量正则：匹配 数字 + 单位（g/kg/oz/lb）
  const weightRegex = /\d+[\.,]?\d*\s*(g|kg|oz|lb)/i;

  for (const part of parts) {
    if (!dimensions && dimensionRegex.test(part)) {
      dimensions = cleanString(part);
    } else if (!weight && weightRegex.test(part)) {
      weight = cleanString(part);
    }
  }

  return [dimensions, weight];
}

/**
 * 解析墨西哥站点特殊尺寸格式
 * @param value 原始尺寸字符串（如 "76,5prof. x 65an. x 76,5alt. centimeters"）
 * @returns [dimensions, weight] 标准化后的尺寸和提取的重量
 */
function parseMexDimensions(value: string): [string, string] {
  // 关键词映射：替换墨西哥站点特有维度缩写
  const keywordMap = {
    "prof.": "",
    "an.": "",
    "alt.": "",
  };

  // 替换关键词和单位
  let processedValue = value.toLowerCase();
  Object.keys(keywordMap).forEach((keyword) => {
    processedValue = processedValue.replace(keyword, "").trim();
  });
  processedValue = processedValue.replace("centimeters", "cm").trim();

  // 提取完整尺寸（数字x数字x数字+单位）
  const dimensionRegex =
    /(\d+[\.,]?\d*\s*x\s*\d+[\.,]?\d*\s*x\s*\d+[\.,]?\d*)\s*(cm|m|in)/i;
  const dimensionMatch = processedValue.match(dimensionRegex);

  if (dimensionMatch) {
    const dimensions = cleanString(dimensionMatch[0]);
    // 从剩余内容中提取重量
    const remainingValue = processedValue.replace(dimensionMatch[0], "").trim();
    const weightRegex = /\d+[\.,]?\d*\s*(g|kg|oz|lb)/i;
    const weightMatch = remainingValue.match(weightRegex);
    const weight = weightMatch ? cleanString(weightMatch[0]) : "";
    return [dimensions, weight];
  }

  // 兜底：若未匹配完整格式，尝试提取3个数字拼接尺寸
  const numberParts = processedValue.match(/\d+[\.,]?\d*/g) || [];
  if (numberParts.length === 3) {
    const dimensions = `${numberParts[0]} x ${numberParts[1]} x ${numberParts[2]} cm`;
    return [dimensions, ""];
  }

  // 提取失败，返回原始处理后的值
  console.warn(`未能标准化墨西哥尺寸: ${value}`);
  return [processedValue, ""];
}

/**
 * 提取墨西哥站点的商品规格信息
 * @param doc Document 对象（DOM文档）
 * @returns [dimensions, weight, brand] 提取的尺寸、重量和品牌信息
 */
function extractMexSpecs(doc: Document): {
  dimensions: string;
  weight: any;
  brand: string;
} {
  let dimensions = "";
  let weight = "";
  let brand = "";

  // console.info("开始提取墨西哥站点的商品规格信息...");

  // 1. 优先处理 po-* 类的表格行
  const poSpecRows = Array.from(doc.querySelectorAll("tr")).filter(
    (tr) => tr.className && tr.className.startsWith("po-")
  );
  // console.debug(`找到 ${poSpecRows.length} 行 po-* 类规格信息`);
  poSpecRows.forEach((row) => {
    const tds = row.querySelectorAll("td");
    if (tds.length >= 2) {
      const labelElem = tds[0].querySelector("span.a-text-bold");
      const valueElem = tds[1].querySelector("span.po-break-word");

      if (labelElem && valueElem) {
        const label = cleanString(labelElem.textContent || "").toLowerCase();
        const value = cleanString(valueElem.textContent || "");
        // console.debug(`解析 po-* 行: 标签='${label}', 值='${value}'`);

        // 提取重量
        if (
          !weight &&
          MEX_WEIGHT_KEYWORDS.some((kw) => label.includes(kw.toLowerCase()))
        ) {
          // console.info(`匹配到重量字段: 原始值='${value}'`);
          weight = normalizeWeight(value, "MEX");
          // console.info(`标准化后的重量: ${weight}`);
        }
        // 提取尺寸（可能包含重量）
        else if (
          !dimensions &&
          MEX_DIMENSION_KEYWORDS.some((kw) => label.includes(kw.toLowerCase()))
        ) {
          // console.info(`匹配到尺寸字段: 原始值='${value}'`);
          const [parsedDimensions, extractedWeight] = parseMexDimensions(value);
          dimensions = parsedDimensions;
          // console.info(
          //   `标准化后的尺寸: ${dimensions}, 提取的重量: ${extractedWeight}`
          // );

          if (extractedWeight && !weight) {
            weight = normalizeWeight(extractedWeight, "MEX");
            // console.info(`标准化后的重量: ${weight}`);
          }
        }
        // 提取品牌
        else if (
          !brand &&
          MEX_BRAND_KEYWORDS.some((kw) => label.includes(kw.toLowerCase()))
        ) {
          // console.info(`匹配到品牌字段: 原始值='${value}'`);
          brand = value;
        }
      }
    }
  });

  // 2. 从 productDetails_techSpec_section_1 表格提取
  const techSpecTable = doc.querySelector(
    "table#productDetails_techSpec_section_1"
  );
  if (techSpecTable) {
    // console.debug("正在解析 #productDetails_techSpec_section_1 表格...");
    techSpecTable.querySelectorAll("tr").forEach((row) => {
      const th = row.querySelector("th");
      const td = row.querySelector("td");
      if (th && td) {
        const header = cleanString(th.textContent || "").toLowerCase();
        const value = cleanString(td.textContent || "");
        // console.debug(`解析表格行: 标题='${header}', 值='${value}'`);

        if (
          !weight &&
          MEX_WEIGHT_KEYWORDS.some((kw) => header.includes(kw.toLowerCase()))
        ) {
          // console.info(`匹配到重量字段: 原始值='${value}'`);
          weight = normalizeWeight(value, "MEX");
          // console.info(`标准化后的重量: ${weight}`);
        } else if (
          !dimensions &&
          MEX_DIMENSION_KEYWORDS.some((kw) => header.includes(kw.toLowerCase()))
        ) {
          // console.info(`匹配到尺寸字段: 原始值='${value}'`);
          const [parsedDimensions, extractedWeight] = parseMexDimensions(value);
          dimensions = parsedDimensions;
          // console.info(
          //   `标准化后的尺寸: ${dimensions}, 提取的重量: ${extractedWeight}`
          // );

          if (extractedWeight && !weight) {
            weight = normalizeWeight(extractedWeight, "MEX");
            // console.info(`标准化后的重量: ${weight}`);
          }
        } else if (
          !brand &&
          MEX_BRAND_KEYWORDS.some((kw) => header.includes(kw.toLowerCase()))
        ) {
          // console.info(`匹配到品牌字段: 原始值='${value}'`);
          brand = value;
        }
      }
    });
  }

  // 3. 从 productDetails_detailBullets_sections1 表格提取
  const detailBulletsTable = doc.querySelector(
    "table#productDetails_detailBullets_sections1"
  );
  if (detailBulletsTable) {
    // console.debug("正在解析 #productDetails_detailBullets_sections1 表格...");
    detailBulletsTable.querySelectorAll("tr").forEach((row) => {
      const th = row.querySelector("th");
      const td = row.querySelector("td");
      if (th && td) {
        const header = cleanString(th.textContent || "").toLowerCase();
        const value = cleanString(td.textContent || "");
        // console.debug(`解析表格行: 标题='${header}', 值='${value}'`);

        if (
          !weight &&
          MEX_WEIGHT_KEYWORDS.some((kw) => header.includes(kw.toLowerCase()))
        ) {
          // console.info(`匹配到重量字段: 原始值='${value}'`);
          weight = normalizeWeight(value, "MEX");
          // console.info(`标准化后的重量: ${weight}`);
        } else if (
          !dimensions &&
          MEX_DIMENSION_KEYWORDS.some((kw) => header.includes(kw.toLowerCase()))
        ) {
          // console.info(`匹配到尺寸字段: 原始值='${value}'`);
          const [parsedDimensions, extractedWeight] =
            splitDimensionWeight(value);
          dimensions = parsedDimensions;
          // console.info(`分离后的尺寸: ${dimensions}, 重量: ${extractedWeight}`);

          if (extractedWeight && !weight) {
            weight = normalizeWeight(extractedWeight, "MEX");
            // console.info(`标准化后的重量: ${weight}`);
          }
        } else if (
          !brand &&
          MEX_BRAND_KEYWORDS.some((kw) => header.includes(kw.toLowerCase()))
        ) {
          // console.info(`匹配到品牌字段: 原始值='${value}'`);
          brand = value;
        }
      }
    });
  }

  // 4. 从 detailBullets_feature_div 区域提取
  const detailBulletsDiv = doc.querySelector("div#detailBullets_feature_div");
  if (detailBulletsDiv) {
    // console.debug("正在解析 #detailBullets_feature_div 区域...");
    detailBulletsDiv.querySelectorAll("li").forEach((li) => {
      const labelElem = li.querySelector("span.a-text-bold");
      // 匹配直接子级的第二个span（无嵌套）
      const valueElem = Array.from(li.children).find(
        (child) => child.tagName === "SPAN" && child !== labelElem
      ) as HTMLSpanElement;

      if (labelElem && valueElem) {
        const label = cleanString(labelElem.textContent || "").toLowerCase();
        const value = cleanString(valueElem.textContent || "");
        // console.debug(`解析列表项: 标签='${label}', 值='${value}'`);

        if (
          !dimensions &&
          MEX_DIMENSION_KEYWORDS.some((kw) => label.includes(kw.toLowerCase()))
        ) {
          // console.info(`匹配到尺寸字段: 原始值='${value}'`);
          const [parsedDimensions, extractedWeight] = parseMexDimensions(value);
          dimensions = parsedDimensions;
          // console.info(
          //   `标准化后的尺寸: ${dimensions}, 提取的重量: ${extractedWeight}`
          // );

          if (extractedWeight && !weight) {
            weight = normalizeWeight(extractedWeight, "MEX");
            // console.info(`标准化后的重量: ${weight}`);
          }
        } else if (
          !weight &&
          MEX_WEIGHT_KEYWORDS.some((kw) => label.includes(kw.toLowerCase()))
        ) {
          // console.info(`匹配到重量字段: 原始值='${value}'`);
          weight = normalizeWeight(value, "MEX");
          // console.info(`标准化后的重量: ${weight}`);
        } else if (
          !brand &&
          MEX_BRAND_KEYWORDS.some((kw) => label.includes(kw.toLowerCase()))
        ) {
          // console.info(`匹配到品牌字段: 原始值='${value}'`);
          brand = value;
        }
      }
    });
  }

  // console.info(
  //   `最终提取结果: 尺寸=${dimensions}, 重量=${weight}, 品牌=${brand}`
  // );
  return { dimensions, weight, brand };
}
// #endregion

// #region [澳大利亚]
// 澳大利亚站点规格提取关键词（英文）
const AUS_DIMENSION_KEYWORDS = [
  "product dimensions",
  "package dimensions",
  "item package dimensions",
  "dimensions",
  "dimension",
];
const AUS_WEIGHT_KEYWORDS = [
  "item weight",
  "weight",
  "package weight",
  "shipping weight",
];
const AUS_BRAND_KEYWORDS = ["brand", "manufacturer"];

/**
 * 标准化澳大利亚站点重量，统一转换为克（g）
 * @param weightStr 原始重量字符串
 * @returns 标准化后的重量字符串（如 "1500g"），未匹配则返回空字符串
 */
function normalizeAusWeight(weightStr: string): string {
  const weightRegex = /(\d+\.?\d*)\s*(kg|kilograms|g|grams)/i;
  const match = weightStr.match(weightRegex);

  if (!match) return "";

  const [, valueStr, unit] = match;
  let value = parseFloat(valueStr);

  // 千克转克
  if (unit.toLowerCase() === "kg" || unit.toLowerCase() === "kilograms") {
    value *= 1000;
  }

  return `${Math.floor(value)}g`;
}

/**
 * 提取澳大利亚站点的商品规格信息（尺寸、重量、品牌）
 * @param doc Document 对象（DOM文档）
 * @returns [dimensions, weight, brand] 提取的规格信息
 */
function normalizeAusDimensions(dimensionsStr: string) {
  return normalizeDimensions(dimensionsStr, "AUS");
}
function extractAusSpecs(doc: Document): {
  dimensions: string;
  weight: any;
  brand: string;
} {
  let dimensions = "";
  let weight = "";
  let brand = "";

  // 1. 优先处理 ul.detail-bullet-list 结构
  const specList = Array.from(doc.querySelectorAll("ul")).find((ul) =>
    ul.classList.contains("detail-bullet-list")
  );
  if (specList) {
    specList.querySelectorAll("li").forEach((li) => {
      const labelSpan = li.querySelector("span.a-text-bold");
      const valueSpan = li.querySelector("span:not([class])"); // 无class的span

      if (labelSpan && valueSpan) {
        const label = cleanString(labelSpan.textContent || "").toLowerCase();
        const value = cleanString(valueSpan.textContent || "");

        // 提取尺寸
        if (
          !dimensions &&
          AUS_DIMENSION_KEYWORDS.some((kw) => label.includes(kw.toLowerCase()))
        ) {
          dimensions = normalizeAusDimensions(value);
        }
        // 提取重量
        else if (
          !weight &&
          AUS_WEIGHT_KEYWORDS.some((kw) => label.includes(kw.toLowerCase()))
        ) {
          weight = normalizeAusWeight(value);
        }
        // 提取品牌
        else if (
          !brand &&
          AUS_BRAND_KEYWORDS.some((kw) => label.includes(kw.toLowerCase()))
        ) {
          brand = value;
        }
      }
    });
  }

  // 2. 处理 productDetails_techSpec_section_1 表格
  const techSpecTable = doc.querySelector(
    "table#productDetails_techSpec_section_1"
  );
  if (techSpecTable) {
    techSpecTable.querySelectorAll("tr").forEach((row) => {
      const th = row.querySelector("th.a-color-secondary");
      const td = row.querySelector("td.a-size-base");

      if (th && td) {
        const label = cleanString(th.textContent || "").toLowerCase();
        const value = cleanString(td.textContent || "");

        // 提取尺寸（取分号前部分）
        if (
          !dimensions &&
          AUS_DIMENSION_KEYWORDS.some((kw) => label.includes(kw))
        ) {
          const dimensionsPart = value.split(";")[0].trim();
          dimensions = normalizeAusDimensions(dimensionsPart);
        }
        // 提取重量
        else if (
          !weight &&
          AUS_WEIGHT_KEYWORDS.some((kw) => label.includes(kw))
        ) {
          weight = normalizeAusWeight(value);
        }
        // 提取品牌
        else if (
          !brand &&
          AUS_BRAND_KEYWORDS.some((kw) => label.includes(kw))
        ) {
          brand = value;
        }
      }
    });
  }

  // 3. 兜底：从 productOverview_feature_div 提取（未获取完全时）
  if (!dimensions || !weight || !brand) {
    const overviewDiv = doc.querySelector("div#productOverview_feature_div");
    if (overviewDiv) {
      overviewDiv.querySelectorAll("tr").forEach((row) => {
        const tds = row.querySelectorAll("td");
        if (tds.length < 2) return;

        const label = cleanString(tds[0].textContent || "").toLowerCase();
        const value = cleanString(tds[1].textContent || "");

        // 提取尺寸
        if (
          !dimensions &&
          AUS_DIMENSION_KEYWORDS.some((kw) => label.includes(kw.toLowerCase()))
        ) {
          dimensions = normalizeAusDimensions(value);
        }
        // 提取重量
        else if (
          !weight &&
          AUS_WEIGHT_KEYWORDS.some((kw) => label.includes(kw.toLowerCase()))
        ) {
          weight = normalizeAusWeight(value);
        }
        // 提取品牌
        else if (
          !brand &&
          AUS_BRAND_KEYWORDS.some((kw) => label.includes(kw.toLowerCase()))
        ) {
          brand = value;
        }
      });
    }
  }

  return { dimensions, weight, brand };
}
// #endregion
// #region [沙特]
// 沙特站点规格提取关键词（阿拉伯语和英语）
const SAU_DIMENSION_KEYWORDS = [
  "أبعاد المنتج",
  "الأبعاد",
  "الحجم",
  "الحجم",
  "السعة",
  "أبعاد الشحنة",
];
const SAU_WEIGHT_KEYWORDS = [
  "الوزن",
  "كيلو غرام",
  "kg",
  "الوزن الصافي",
  "وزن السلعة",
];
const SAU_BRAND_KEYWORDS = [
  "العلامة التجارية",
  "الشركة المصنعة",
  "العلامة",
  "ماركة",
];

/**
 * 标准化沙特站点的尺寸字符串（对应Python的normalize_sau_dimensions）
 * @param dimStr 原始尺寸字符串
 * @returns 标准化后的尺寸字符串
 */
function normalizeSauDimensions(dimStr: string): string {
  if (!dimStr) return "";

  // 清理不可见字符和特殊符号
  let normalized = dimStr
    .normalize("NFKC") // 统一Unicode字符（对应Python的unicodedata.normalize）
    .replace(/‎/g, "") // 移除不可见字符
    .replace(/;/g, "") // 移除分号
    .trim();

  // 替换阿拉伯语单位和描述词
  normalized = normalized
    .replace(/العمق|العرض|الارتفاع/gi, "") // 移除维度描述词
    .replace(/سم/gi, "cm") // 阿拉伯语单位转英文
    .trim();

  // 替换标点符号
  normalized = normalized
    .replace(/،/g, ".") // 阿拉伯语逗号转点号
    .replace(/,/g, "."); // 英文逗号转点号

  // 提取所有数字（支持小数点，对应Python的re.findall）
  const numberParts = normalized.match(/\d+\.?\d*/g) || [];

  // 标准化为 "数字 x 数字 x 数字 cm" 格式
  if (numberParts.length >= 3) {
    return `${numberParts[0]} x ${numberParts[1]} x ${numberParts[2]} cm`;
  }

  console.warn(`未能标准化尺寸字段: ${dimStr}`);
  return dimStr;
}

/**
 * 从尺寸字符串中提取重量（对应Python的extract_weight_from_dimension）
 * @param dimStr 尺寸字符串
 * @returns 提取的重量（克为单位，未识别返回0）
 */
function extractWeightFromDimension(dimStr: string): number {
  if (!dimStr) return 0;

  const gWeightRegex = /(\d+[.,]?\d*)\s*(جرام|g|gram)/gi;
  const gWeightMatch = gWeightRegex.exec(dimStr);
  if (gWeightMatch) {
    const gWeightValue = gWeightMatch[1].replace(",", ".");
    try {
      const gramValue = Math.round(parseFloat(gWeightValue));
      if (gramValue > 0) {
        return gramValue;
      }
    } catch {}
  }

  // 匹配重量信息（支持阿拉伯语和英语单位，对应Python的re.search）
  const kgWeightRegex = /(\d+[.,]?\d*)\s*(كيلو غرام|kg|كيلو|كغم|kilogram)/gi;
  const kgWeightMatch = kgWeightRegex.exec(dimStr);

  if (kgWeightMatch) {
    // 替换逗号为点号，转换为克并取整
    const kgWeightValue = kgWeightMatch[1].replace(",", ".");
    try {
      const gramValue = Math.round(parseFloat(kgWeightValue) * 1000);
      return gramValue;
    } catch (error) {
      // console.warn(`无法转换重量值: ${kgWeightValue}`);
      return 0;
    }
  }

  // console.warn(`未能从尺寸字段中提取重量: ${dimStr}`);
  return 0;
}

/**
 * 提取沙特站点的商品规格信息（对应Python的extract_sau_specs）
 * @param doc 浏览器DOM Document对象
 * @returns 数组 [dimensions, weight, brand]，未找到则返回空字符串
 */
function extractSauSpecs(doc: Document): {
  dimensions: string;
  weight: any;
  brand: string;
} {
  let dimensions = "";
  let weight: number | string = ""; // 支持数字（克）或字符串格式
  let brand = "";

  // --------------------------
  // 1. 优先处理技术规格表格（productDetails_techSpec_section_1）
  // --------------------------
  const techSpecTable = doc.getElementById("productDetails_techSpec_section_1");
  if (techSpecTable) {
    const rows = techSpecTable.querySelectorAll("tr");
    rows.forEach((row) => {
      const th = row.querySelector("th");
      const td = row.querySelector("td");
      if (!th || !td) return;

      const label = cleanString(th.textContent || "").toLowerCase();
      const value = cleanString(td.textContent || "");

      // 匹配尺寸字段
      if (
        !dimensions &&
        SAU_DIMENSION_KEYWORDS.some((kw) => label.includes(kw.toLowerCase()))
      ) {
        dimensions = normalizeSauDimensions(value);
        // 从尺寸中提取重量（未找到时）
        if (!weight) {
          weight = extractWeightFromDimension(value);
        }
      }
      // 匹配重量字段
      else if (
        !weight &&
        SAU_WEIGHT_KEYWORDS.some((kw) => label.includes(kw.toLowerCase()))
      ) {
        weight = normalizeWeight(value, "SAU");
      }
      // 匹配品牌字段
      else if (
        !brand &&
        SAU_BRAND_KEYWORDS.some((kw) => label.includes(kw.toLowerCase()))
      ) {
        brand = value;
      }
    });
  }

  // --------------------------
  // 2. 未找全则处理其他表格（a-keyvalue、prodDetTable）
  // --------------------------
  if (!(dimensions && weight && brand)) {
    const otherTables = doc.querySelectorAll(
      "table.a-keyvalue, table.prodDetTable"
    );
    otherTables.forEach((table) => {
      // 跳过已处理的主表格
      if (table.id === "productDetails_techSpec_section_1") return;

      const rows = table.querySelectorAll("tr");
      rows.forEach((row) => {
        const th = row.querySelector("th");
        const td = row.querySelector("td");
        if (!th || !td) return;

        const label = cleanString(th.textContent || "").toLowerCase();
        const value = cleanString(td.textContent || "");

        // 匹配尺寸字段（分号分割时取第一个）
        if (
          !dimensions &&
          SAU_DIMENSION_KEYWORDS.some((kw) => label.includes(kw.toLowerCase()))
        ) {
          dimensions = value.includes(";") ? value.split(";")[0].trim() : value;
          // 从尺寸中提取重量（未找到时）
          if (!weight) {
            weight = extractWeightFromDimension(value);
          }
        }
        // 匹配重量字段
        else if (
          !weight &&
          SAU_WEIGHT_KEYWORDS.some((kw) => label.includes(kw.toLowerCase()))
        ) {
          weight = normalizeWeight(value, "SAU");
        }
        // 匹配品牌字段
        else if (
          !brand &&
          SAU_BRAND_KEYWORDS.some((kw) => label.includes(kw.toLowerCase()))
        ) {
          brand = value;
        }
      });
    });
  }

  // --------------------------
  // 3. 未找全则回退到列表结构（detail-bullet-list）
  // --------------------------
  if (!(dimensions && weight && brand)) {
    const detailBullets = doc.querySelector('ul[class*="detail-bullet-list"]');
    if (detailBullets) {
      const lis = detailBullets.querySelectorAll("li");
      lis.forEach((li) => {
        const labelSpan = li.querySelector("span.a-text-bold");
        const valueSpan = li.querySelector("span:not([class])"); // 无class的span
        if (!labelSpan || !valueSpan) return;

        const label = cleanString(labelSpan.textContent || "").toLowerCase();
        const value = cleanString(valueSpan.textContent || "");

        // 匹配尺寸字段（分号分割时取第一个）
        if (
          !dimensions &&
          SAU_DIMENSION_KEYWORDS.some((kw) => label.includes(kw.toLowerCase()))
        ) {
          dimensions = value.includes(";") ? value.split(";")[0].trim() : value;
          // 从尺寸中提取重量（未找到时）
          if (!weight) {
            weight = extractWeightFromDimension(value);
          }
        }
        // 匹配重量字段
        else if (
          !weight &&
          SAU_WEIGHT_KEYWORDS.some((kw) => label.includes(kw.toLowerCase()))
        ) {
          weight = normalizeWeight(value, "SAU");
        }
        // 匹配品牌字段
        else if (
          !brand &&
          SAU_BRAND_KEYWORDS.some((kw) => label.includes(kw.toLowerCase()))
        ) {
          brand = value;
        }
      });
    }
  }

  // --------------------------
  // 4. 未找全则尝试po-*类表格
  // --------------------------
  if (!(dimensions && weight && brand)) {
    const poSpecRows = doc.querySelectorAll('tr[class^="po-"]'); // class以po-开头的tr
    poSpecRows.forEach((row) => {
      const tds = row.querySelectorAll("td");
      if (tds.length < 2) return;

      const labelElem = tds[0].querySelector("span.a-text-bold");
      const valueElem = tds[1].querySelector("span.po-break-word");
      if (!labelElem || !valueElem) return;

      const label = cleanString(labelElem.textContent || "").toLowerCase();
      const value = cleanString(valueElem.textContent || "");

      // 匹配尺寸字段
      if (
        !dimensions &&
        SAU_DIMENSION_KEYWORDS.some((kw) => label.includes(kw.toLowerCase()))
      ) {
        dimensions = normalizeSauDimensions(value);
        // 从尺寸中提取重量（未找到时）
        if (!weight) {
          weight = extractWeightFromDimension(value);
        }
      }
      // 匹配重量字段
      else if (
        !weight &&
        SAU_WEIGHT_KEYWORDS.some((kw) => label.includes(kw.toLowerCase()))
      ) {
        weight = normalizeWeight(value, "SAU");
      }
      // 匹配品牌字段
      else if (
        !brand &&
        SAU_BRAND_KEYWORDS.some((kw) => label.includes(kw.toLowerCase()))
      ) {
        brand = value;
      }
    });
  }

  // 统一重量格式：数字0转为空字符串（保持返回值类型统一）
  return { dimensions, weight, brand };
}
// #endregion

// #region [法国]
const FRANCE_DIMENSION_KEYWORDS = [
  "dimension",
  "dimensions",
  "size",
  "尺寸",
  "规格",
  "dimensions du produit",
];
const FRANCE_DIMENSION_EXACT_MATCH_KEYWORDS = ["taille du", "taille"];
const FRANCE_WEIGHT_KEYWORDS = [
  "weight",
  "重量",
  "poids de",
  "poids de l'article",
  "poids du produit",
];
const FRANCE_BRAND_KEYWORDS = ["brand", "品牌", "marque"];

function normalizeFraDimensions(dimensionsStr: string) {
  const [dimensionsStrValue] = dimensionsStr.split(";");
  return normalizeDimensions(dimensionsStrValue, "FRA");
}
function normalizeFraWeight(weightStr: string): string {
  return normalizeWeight(weightStr, "FRA");
}

function extractFraSpecs(doc: Document): {
  dimensions: string;
  weight: any;
  brand: string;
} {
  let dimensions = "";
  let weight: number | string = "";
  let brand = "";

  // 1. 优先处理通用表格结构（匹配class包含'detail-bullet-list'的ul）
  const specList = doc.querySelector('ul[class*="detail-bullet-list"]');
  if (specList) {
    // 遍历所有li元素（对应Python的spec_list.find_all('li')）
    const liElements = specList.querySelectorAll("li");
    liElements.forEach((li) => {
      // 查找带a-text-bold类的标签（对应Python的label_span）
      const labelSpan = li.querySelector("span.a-text-bold");
      // 查找无class的span标签（对应Python的value_span，class为None）
      const valueSpan = li.querySelector("span:not([class])");

      if (labelSpan && valueSpan) {
        const label = cleanString(labelSpan.textContent || "").toLowerCase().replace(/[ :]/g, "");
        const value = cleanString(valueSpan.textContent || "");

        // 匹配尺寸关键词（未找到时才赋值）
        if (
          !dimensions &&
          (FRANCE_DIMENSION_KEYWORDS.some((kw) =>
            label.includes(kw.toLowerCase())
          ) ||
            FRANCE_DIMENSION_EXACT_MATCH_KEYWORDS.some(
              (kw) => label === kw.toLowerCase()
            ))
        ) {
          dimensions = normalizeFraDimensions(value);
          if (!weight) {
            weight = extractWeightFromDimension(value);
          }
        }
        // 匹配重量关键词（未找到时才赋值）
        else if (
          !weight &&
          FRANCE_WEIGHT_KEYWORDS.some((kw) => label.includes(kw.toLowerCase()))
        ) {
          weight = normalizeWeight(value, "FRA");
        }
        // 匹配品牌/制造商关键词（未找到时才赋值）
        else if (
          !brand &&
          FRANCE_BRAND_KEYWORDS.some((kw) => label.includes(kw.toLowerCase()))
        ) {
          brand = value;
        }
      }
    });
  }

  // 2. 处理 productDetails_techSpec_section_1 表格
  const techSpecTable = doc.querySelector(
    "table#productDetails_techSpec_section_1"
  );
  if (techSpecTable) {
    techSpecTable.querySelectorAll("tr").forEach((row) => {
      const th = row.querySelector("th.a-color-secondary");
      const td = row.querySelector("td.a-size-base");

      if (th && td) {
        const label = cleanString(th.textContent || "").toLowerCase().replace(/[ :]/g, "");
        const value = cleanString(td.textContent || "");

        // 提取尺寸（取分号前部分）
        if (
          !dimensions &&
          (FRANCE_DIMENSION_KEYWORDS.some((kw) =>
            label.includes(kw.toLowerCase())
          ) ||
            FRANCE_DIMENSION_EXACT_MATCH_KEYWORDS.some(
              (kw) => label === kw.toLowerCase()
            ))
        ) {
          const dimensionsPart = value.split(";")[0].trim();
          dimensions = normalizeFraDimensions(dimensionsPart);
          if (!weight) {
            weight = extractWeightFromDimension(value);
          }
        }
        // 提取重量
        else if (
          !weight &&
          FRANCE_WEIGHT_KEYWORDS.some((kw) => label.includes(kw))
        ) {
          weight = normalizeFraWeight(value);
        }
        // 提取品牌
        else if (
          !brand &&
          FRANCE_BRAND_KEYWORDS.some((kw) => label.includes(kw))
        ) {
          brand = value;
        }
      }
    });
  }

  // 3. 兜底：从 productOverview_feature_div 提取（未获取完全时）
  if (!dimensions || !weight || !brand) {
    const overviewDiv = doc.querySelector("div#productOverview_feature_div");
    if (overviewDiv) {
      overviewDiv.querySelectorAll("tr").forEach((row) => {
        const tds = row.querySelectorAll("td");
        if (tds.length < 2) return;

        const label = cleanString(tds[0].textContent || "").toLowerCase().replace(/[ :]/g, "");
        const value = cleanString(tds[1].textContent || "");

        // 提取尺寸
        if (
          !dimensions &&
          (FRANCE_DIMENSION_KEYWORDS.some((kw) =>
            label.includes(kw.toLowerCase())
          ) ||
            FRANCE_DIMENSION_EXACT_MATCH_KEYWORDS.some(
              (kw) => label === kw.toLowerCase()
            ))
        ) {
          dimensions = normalizeFraDimensions(value);
          if (!weight) {
            weight = extractWeightFromDimension(value);
          }
        }
        // 提取重量
        else if (
          !weight &&
          FRANCE_WEIGHT_KEYWORDS.some((kw) => label.includes(kw.toLowerCase()))
        ) {
          weight = normalizeFraWeight(value);
        }
        // 提取品牌
        else if (
          !brand &&
          FRANCE_BRAND_KEYWORDS.some((kw) => label.includes(kw.toLowerCase()))
        ) {
          brand = value;
        }
      });
    }
  }

  return { dimensions, weight, brand };
}
// #endregion

// #region [通用]

// 定义尺寸和重量关键词（对应Python的self.DIMENSION_KEYWORDS、self.WEIGHT_KEYWORDS，可根据需求调整）
const GENERIC_DIMENSION_KEYWORDS = [
  "dimension",
  "dimensions",
  "size",
  "尺寸",
  "规格",
];
const GENERIC_WEIGHT_KEYWORDS = ["weight", "重量"];

/**
 * 提取通用的商品规格信息（适用于未明确指定市场的场景）
 * @param doc 浏览器DOM Document对象
 * @returns 数组 [dimensions, weight, brand]，未找到则返回空字符串
 */
function extractGenericSpecs(doc: Document): {
  dimensions: string;
  weight: any;
  brand: string;
} {
  let dimensions = "";
  let weight = "";
  let brand = "";

  // 1. 优先处理通用表格结构（匹配class包含'detail-bullet-list'的ul）
  const specList = doc.querySelector('ul[class*="detail-bullet-list"]');
  if (specList) {
    // 遍历所有li元素（对应Python的spec_list.find_all('li')）
    const liElements = specList.querySelectorAll("li");
    liElements.forEach((li) => {
      // 查找带a-text-bold类的标签（对应Python的label_span）
      const labelSpan = li.querySelector("span.a-text-bold");
      // 查找无class的span标签（对应Python的value_span，class为None）
      const valueSpan = li.querySelector("span:not([class])");

      if (labelSpan && valueSpan) {
        const label = cleanString(labelSpan.textContent || "").toLowerCase();
        const value = cleanString(valueSpan.textContent || "");

        // 匹配尺寸关键词（未找到时才赋值）
        if (
          !dimensions &&
          GENERIC_DIMENSION_KEYWORDS.some((kw) =>
            label.includes(kw.toLowerCase())
          )
        ) {
          dimensions = value;
        }
        // 匹配重量关键词（未找到时才赋值）
        else if (
          !weight &&
          GENERIC_WEIGHT_KEYWORDS.some((kw) => label.includes(kw.toLowerCase()))
        ) {
          weight = normalizeWeight(value);
        }
        // 匹配品牌/制造商关键词（未找到时才赋值）
        else if (
          !brand &&
          ["brand", "manufacturer"].some((kw) =>
            label.includes(kw.toLowerCase())
          )
        ) {
          brand = value;
        }
      }
    });
  }

  return { dimensions, weight, brand };
}

// #endregion

// #region [尺寸重量品牌]
export function extractProductSpecs(
  doc: Document,
  marketplace: string
): {
  dimensions: string;
  weight: any;
  brand: string;
} {
  try {
    if (marketplace === "USA") {
      return extractUsaSpecs(doc);
    } else if (marketplace === "JPN") {
      return extractJpnSpecs(doc);
    } else if (marketplace === "DEU") {
      return extractDeuSpecs(doc);
    } else if (marketplace === "MEX") {
      return extractMexSpecs(doc);
    } else if (marketplace === "AUS") {
      return extractAusSpecs(doc);
    } else if (marketplace === "SAU") {
      return extractSauSpecs(doc);
    } else if (marketplace === "FRA") {
      return extractFraSpecs(doc);
    }
    return extractGenericSpecs(doc);
  } catch (error) {
    console.log("error", error);
    return { dimensions: "", weight: "", brand: "" };
  }
}

// #endregion
